<?php

namespace App\V3\V3_2_7\Controllers;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\SerialNumberModel;
use App\V3\V3_2_7\Services\BarterService;
use App\V3\V3_2_7\Services\MaterielService;
use App\V3\V3_2_7\Services\ScanCodeAllotService;
use App\V3\V3_2_7\Services\StorageManageService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Services\SmsService;
use Illuminate\Support\Facades\Redis;
use App\V3\V3_2_7\Models\StorageBatchModel;
use App\V3\V3_2_7\Services\SellService;
use function OpenApi\push;
use OSS\OssClient;

class StorageManageController extends BaseController
{
    /**
     * 库存列表-库位模式
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/19 15:06
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);
        ini_set("memory_limit", "256M");
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $mainId = [];
        $storageIdArr = [];
        if ($this->getUserId() === $this->getMainUserId()) {
            $mainId['storage_manage.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            if ($this->getUserId() === 19158) {
                $mainId['storage_manage.main_id'] = ['EQ' => $this->getMainUserId()];
            } else {
                if ($this->isShareStorage()) {
                    $mainId['storage_manage.main_id'] = ['EQ' => $this->getMainUserId()];
                } else {
                    $userInfo = [
                        'main_id' => $this->getMainUserId(),
                        'user_id' => $this->getUserId()
                    ];
                    $storageIdArr = CommonService::getMultiUser($userInfo);
                    if (empty($storageIdArr)) {
                        $mainId['e.user_id'] = ['EQ' => $this->getUserId()];
                    } else {
                        $mainId['storage_manage.main_id'] = ['EQ' => $this->getMainUserId()];
                    }
                }
            }
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['user_type'] = $this->getUserTpye();
        $data['is_share_storage_operate'] = $this->isShareStorageOperate();
        $data['order_type'] = empty($data['order_type']) ? 0 : $data['order_type'];

        if (!in_array($data['order_type'], [0, 1, 2])) {
            return $this->fail('', '不支持的排序类型');
        }

        $data['order_by'] = empty($data['order_by']) ? 'asc' : $data['order_by'];

        if (!in_array($data['order_by'], ['desc', 'asc'])) {
            return $this->fail('', '不支持的排序方式');
        }
        if ($data['user_id'] === 19158) $data['user_id'] = 52;
        return $this->success(StorageManageService::list($mainId, $data, $storageIdArr));

    }

    /**
     * 库存列表-仓库模式
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2024/5/9 15:06
     * @return \Illuminate\Http\JsonResponse
     */
    public function warehouseInventoryList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);
        ini_set("memory_limit", "256M");
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $mainId = [];
        $storageIdArr = [];
        if ($this->getUserId() == $this->getMainUserId()) {
            $mainId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            if ($this->isShareStorage()) {
                $mainId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            } else {
                $userInfo = [
                    'main_id' => $this->getMainUserId(),
                    'user_id' => $this->getUserId()
                ];
                $storageIdArr = CommonService::getMultiUser($userInfo);
                if (empty($storageIdArr)) {
                    $mainId['a.user_id'] = ['EQ' => $this->getUserId()];
                } else {
                    $mainId['a.main_id'] = ['EQ' => $this->getMainUserId()];
                }
            }
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['user_type'] = $this->getUserTpye();
        $data['is_share_storage_operate'] = $this->isShareStorageOperate();
        $data['order_type'] = empty($data['order_type']) ? 0 : $data['order_type'];

        if (!in_array($data['order_type'], [0, 1, 2])) {
            return $this->fail('', '不支持的排序类型');
        }

        $data['order_by'] = empty($data['order_by']) ? 'asc' : $data['order_by'];

        if (!in_array($data['order_by'], ['desc', 'asc'])) {
            return $this->fail('', '不支持的排序方式');
        }

        return $this->success(StorageManageService::warehouseInventoryList($mainId, $data, $storageIdArr));

    }

    /**
     * 库存列表-仓库模式
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2024/5/9 15:06
     * @return \Illuminate\Http\JsonResponse
     */
    public function newInventoryList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);
        ini_set("memory_limit", "256M");
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $mainId = [];
        $storageIdArr = [];
        if ($this->getUserId() == $this->getMainUserId()) {
            $mainId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            if ($this->isShareStorage()) {
                $mainId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            } else {
                $userInfo = [
                    'main_id' => $this->getMainUserId(),
                    'user_id' => $this->getUserId()
                ];
                $storageIdArr = CommonService::getMultiUser($userInfo);
                if (empty($storageIdArr)) {
                    $mainId['e.user_id'] = ['EQ' => $this->getUserId()];
                } else {
                    $mainId['a.main_id'] = ['EQ' => $this->getMainUserId()];
                }
            }
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['user_type'] = $this->getUserTpye();
        $data['is_share_storage_operate'] = $this->isShareStorageOperate();
        $data['order_type'] = empty($data['order_type']) ? 0 : $data['order_type'];

        if (!in_array($data['order_type'], [0, 1, 2])) {
            return $this->fail('', '不支持的排序类型');
        }

        $data['order_by'] = empty($data['order_by']) ? 'asc' : $data['order_by'];

        if (!in_array($data['order_by'], ['desc', 'asc'])) {
            return $this->fail('', '不支持的排序方式');
        }

        return $this->success(StorageManageService::newInventoryList($mainId, $data, $storageIdArr));

    }

    /**
     * 批次列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 16:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//页面大小
        ], [
            'id.required' => '参数`库存主键id`缺失',
            'id.integer' => '参数`库存主键id`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $result = StorageManageService::batchList($request->id);
        if (!empty($result['batch_list'])) {
            $oneDay = 24 * 3600;
            foreach ($result['batch_list'] as &$value) {
                $value['expire_flag'] = 0;
                if (!empty($value['production_time'])) {
                    if (!empty($value['expiration_date'])) {//保质期
                        $expirationDate = $value['expiration_date'] * $oneDay;//保质期的时间戳
                        $expirationTime = strtotime($value['production_time']) + $expirationDate;//过期时间的时间戳
                        $timeRemaining = $expirationTime - time();//剩余时间
                        if (!empty($value['warning_time']) && $timeRemaining > 0) {//预警时间设置
                            $day = $timeRemaining / $oneDay;//剩余天数
                            if ($day <= $value['warning_time']) {
                                $value['expire_flag'] = 1;
                            }
                        } elseif ($timeRemaining <= 0) {
                            $value['expire_flag'] = 1;
                        }
                    }
                }
                $value['upload_credentials_img'] = !empty($value['upload_credentials_img']) ? explode(',', $value['upload_credentials_img']) : [];
            }
        }
        return response()->json(['code' => 0, 'msg' => 'success', 'data' => $result]);
    }

    /**
     * 批次采购详细
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 16:23
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchMaterielInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//页面大小
        ], [
            'id.required' => '参数`批次主键id`缺失',
            'id.integer' => '参数`批次主键id`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $result = StorageManageService::batchMaterielInfo($request->id);

        if (!empty($result['upload_credentials_img'])) {
            $result['upload_credentials_img'] = preg_split("/,/", $result['upload_credentials_img']);
        } else {
            $result['upload_credentials_img'] = [];
        }
        $oneDay = 24 * 3600;
        $result['expire_flag'] = 0;
        if (!empty($result['production_time'])) {
            if (!empty($result['expiration_date'])) {//保质期
                $expirationDate = $result['expiration_date'] * $oneDay;//保质期的时间戳
                $expirationTime = strtotime($result['production_time']) + $expirationDate;//过期时间的时间戳
                $timeRemaining = $expirationTime - time();//剩余时间
                if (!empty($result['warning_time']) && $timeRemaining > 0) {//预警时间设置
                    $day = $timeRemaining / $oneDay;//剩余天数
                    if ($day <= $result['warning_time']) {
                        $result['expire_flag'] = 1;
                    }
                } elseif ($timeRemaining <= 0) {
                    $result['expire_flag'] = 1;
                }
            }
        }

        if (!empty(strtotime($result['production_time'])) && !empty($result['warning_time']) && !empty($result['expiration_date'])) {
            $warningTime = strtotime($result['production_time']) + ($result['expiration_date'] - $result['warning_time']) * 3600;
            $result['warning_time'] = date('Y-m-d H:i:s', $warningTime);
        }

        return $this->success($result);
    }

    public function readBatchNo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'batch_no' => 'required',//条码信息
        ], [
            'batch_no.required' => '参数`条码信息`缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(
            StorageManageService::readBatchNo($data)
        );
    }

    /**
     * 商品库存批次列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/24 15:55
     * @return \Illuminate\Http\JsonResponse
     */
    public function materielBatchList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'materiel_type_id' => 'required',//页面大小
            'sell_id' => 'required',
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//条码类型0:商品;1:套餐;
        ], [
            'materiel_type_id.required' => '参数`商品id`缺失',
            'sell_id.required' => '参数`销售单id`缺失',
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return $this->success(
            StorageManageService::materielBatchList(
                $request->materiel_type_id,
                $request->sell_id,
                $request->type,
                $data
            )
        );
    }

    public function fastOutStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'batch_no' => 'required',//页面大小
            'code_type' => 'required',
            'storage_id' => 'required|integer',//仓库id
            /*  'shelf_id' => 'required|integer',//入库货架ID
              'location_id' => 'required|integer',//入库库位ID*/
        ], [
            'batch_no.required' => '参数`编号`缺失',
            'code_type.required' => '参数`码的类型`缺失',
            /*'shelf_id.required' => '参数`货架ID`缺失',
            'location_id.required' => '参数`库位ID`缺失',
            'shelf_id.integer' => '参数`货架ID`,必须为整数！',
            'location_id.integer' => '参数`库位ID`,必须为整数！',*/
            'storage_id.required' => '参数`库存主键id`缺失',
            'storage_id.integer' => '参数`库存主键id`仅能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['out_way'] = $this->getOutWay();
        $data['batch_title'] = $this->batchTitle();
        $time = time();
        $this->operateLog('商品或套餐快速出库', $data, $time);

        /**
         * form_type:   0   销售单
         *              1   报溢报损
         *              2   退货
         */
        $formType = isset($data['form_type']) ? $data['form_type'] : 0;
        $data['time'] = $time;
        return response()->json(
            StorageManageService::fastOutStorage($data, $formType)
        );
    }

    /**
     * 清除批次信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/7/13 16:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function clear(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//页面大小
        ], [
            'id.required' => '参数`库存主键id`缺失',
            'id.integer' => '参数`库存主键id`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        return response()->json(
            StorageManageService::clear($data)
        );
    }

    /**
     * 直接入库（批量）
     */
    public function directInStorageSeveral(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'goods_info' => 'required'
        ], [
            'goods_info.required' => '请选择，入库商品！'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['is_use_shelf'] = $this->isUseShelf();
        $data['is_use_packages_components'] = $this->isUsePackagesComponents();
        $data['is_share_shelf_location'] = $this->isShareShelfLocation();
        $data['label_id'] = empty($data['label_id']) ? '' : $data['label_id'];
        $data['label_name'] = empty($data['label_name']) ? '' : $data['label_name'];
        $time = time();
        $data['in_storage_time'] = empty($data['in_storage_time']) ? $time : strtotime($data['in_storage_time']);
        $this->operateLog('快速入库', $data, $time);
        $result = StorageManageService::directInStorageSeveral($data, $time);
        return response()->json($result);
    }

    /**
     * 直接出库或批量出库
     * Author: Sw
     * Created at 2023/3/8 17:24
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function directOutStorageSeveral(Request $request)
    {
        $data = $request->all();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['is_use_shelf'] = $this->isUseShelf();
        $data['is_share_shelf_location'] = $this->isShareShelfLocation();
        $data['label_id'] = $data['label_id'] ?? '';
        $data['label_name'] = $data['label_name'] ?? '';
        $data['is_use_packages_components'] = $this->isUsePackagesComponents();
        $time = time();
        $this->operateLog('直接出库', $data, $time);
        $data['out_storage_time'] = empty($data['out_storage_time']) ? $time : strtotime($data['out_storage_time']);
        $result = StorageManageService::directOutStorageSeveral($data, $time);
        return response()->json($result);
    }

    /**
     * 批量生成批次号
     */
    public function createBatchNoList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type_ids' => 'required'
        ], ['type_ids.required' => '商品ID，不能为空 ']);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $batchList = [];
        $data['batch_title'] = $this->batchTitle();
        $idsArr = array_filter(explode(',', $data['type_ids']), function ($v) {
            return $v !== '';
        });
        if (!empty($idsArr) && is_array($idsArr)) {
            foreach ($idsArr as $key => $val) {
                $batchNo = $data['batch_title'] . date('YmdHis', time()) . mt_rand(1000, 9999) . '0';
                do {
                    $batchNo = $data['batch_title'] . date('YmdHis', time()) . mt_rand(1000, 9999) . '0';
                } while (!empty(StorageBatchModel::where('batch_no', $batchNo)->first()));
                $batchList[] = [
                    'type_id' => $val,
                    'batch_no' => $batchNo
                ];
            }
            return response()->json([
                'code' => 0,
                'msg' => 'success',
                'data' => ['batch_list' => $batchList],
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '商品信息有误',
                'data' => '',
            ]);
        }
    }

    /**
     * 批次列表
     */
    public function serialNoList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storageManageId' => 'required|numeric',//库存id
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $list = SerialNumberModel::select('serial_no')->where([
            'storage_manage_id' => $data['storageManageId'],
            'status' => SerialNumberModel::UNUSEDSTATUS,
            'delete_flag' => 0
        ]);

        if ($data['search_data']) {
            $list->where('serial_no', 'like', '%' . $data['search_data'] . '%');
        }

        $list = $list->paginate($data['pageSize'], ['*'], '', $data['currentPage']);

        return response()->json(
            ['code' => 0, 'msg' => 'success', 'data' => $list]
        );
    }

    /**
     * 一键清除
     * @param Request $request
     * 2022/9/8 11:00
     * Author: Sun Wu
     * @return \Illuminate\Http\JsonResponse
     */
    public function oneKeyClear(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'clear_storage' => [
                Rule::In([0, 1]),
            ],//清理库存
            'clear_materiel' => [
                Rule::In([0, 1]),
            ],//清理商品
            'clear_class' => [
                Rule::In([0, 1]),
            ],//清理分类
            'code' => 'required',
            'mobile' => 'required',
        ], [
            'clear_storage.in' => '参数`清理库存`异常',
            'clear_materiel.in' => '参数`清理商品`异常',
            'clear_class.in' => '参数`clear_class`异常',
            'code.required' => '`验证码`不能为空',
            'mobile.required' => '`手机号`不能为空',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $result = self::checkMobile($data);//校验手机号

        if (!$result == '') {
            return response()->json([
                'code' => 1,
                'msg' => $result,
                'data' => ''
            ]);
        }

        $time = time();
        $data['logTime'] = $time;
        $this->operateLog('一键清除', $data, $time);
        $result = StorageManageService::oneKeyClear($data);
        CommonService::operateResult($data['main_id'], $time, $result);
        return response()->json(
            $result
        );
    }

    /**
     * 返回主账号手机号（一键清除发送验证码）
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2022/09/23 10:06
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMainPhone(Request $request)
    {

        if ($this->getUserId() == $this->getMainUserId() || $this->getMainUserId() == 0) {

            $adminInfo = AdminModel::select('mobile')->where('id', $this->getUserId())->first();

        } else {

            $adminInfo = AdminModel::select('mobile')->where('id', $this->getMainUserId())->first();
        }
        $this->log('一键清除-返回主账号手机号', $adminInfo);
        return $this->success($adminInfo);
    }

    /**
     * 一键清除发送验证码
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2022/09/23 10:06
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOneClearCode(Request $request)
    {

        $result = self::checkMobile($request->all());//校验手机号

        if ($result == '') {
            if (Redis::exists($request->mobile . '_one_clear')) {

                return response()->json([
                    'code' => 1,
                    'msg' => '验证码已发送，请勿重新点击',
                    'data' => ''
                ]);
            }
            return response()->json(SmsService::sendOneClearCode($request->mobile, config('app.one_clear_temp_id')));
        } else {
            return response()->json([
                'code' => 1,
                'msg' => $result,
                'data' => ''
            ]);
        }

    }

    //校验手机号
    public function checkMobile($data)
    {
        $messages = [
            'mobile.required' => '手机号不能为空，请输入手机号',
            'mobile.regex' => '手机号格式错误，请重试',
        ];

        $validator = Validator::make($data, [
            'mobile' => 'required|regex:/^1[3456789][0-9]{9}$/',
        ], $messages);

        return $validator->errors()->first();
    }

    /**
     * 库存直接入库-库位模式
     * @param Request $request
     * 2022/9/8 17:32
     * Author: Sun Wu
     * @return \Illuminate\Http\JsonResponse
     */
    public function storageManageIn(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//页面大小
            'num' => 'required|numeric|min:0'
        ], [
            'id.required' => '参数`库存主键id`缺失',
            'id.integer' => '参数`库存主键id`仅能为数字',
            'num.required' => '参数`数量`缺失',
            'num.numeric' => '参数`数量`仅能为数字',
            'num.min' => '参数`数量`最小仅能为0',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['time'] = time();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['label_id'] = empty($data['label_id']) ? '' : $data['label_id'];

//        $this->log('库存直接入库',var_export($data, true));
        $this->operateLog('库存直接入库', $data, $data['time']);

        $result = StorageManageService::storageManageIn($data);
        CommonService::operateResult($data['user_id'], $data['time'], $result);
        return response()->json(
            $result
        );
    }

    /**
     * @直接入库
     * @created 在 2021/11/30 11:30 创建
     * @param Request $request
     * @author: Sun Wu
     */
    public function directInStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'materiel_name' => 'required',//物料名称
//            'type_name' => 'required',//物料型号
            'storage_id' => 'required|numeric',//仓库id
            'storage_name' => 'required',//仓库名
            'status' => [
                'required',
                Rule::In([0, 1]),
            ],//是否设置低库存预警数：0-否 1-是
//            'in_storage_time' => 'required|date_format:Y-m-d H:i:s',//入库时间
            'num' => 'required|numeric|min:0',//入库数量
            'alert_num' => 'numeric|min:0'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $this->log('新建直接入库', $data);
        return response()->json(
            StorageManageService::directInStorage($data)
        );
    }

    /**
     * @扫码入库
     * @created 在 2023/2/22 13:47 创建
     * @param Request $request
     * @author: zlf
     */
    public function scanCodesInStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storage_id' => 'required|integer',//仓库id
            /*  'shelf_id' => 'required|integer',//入库货架ID
              'location_id' => 'required|integer',//入库库位ID*/
            'batch_no' => 'required',
            'code_type' => [
                'required',
                Rule::In([0, 1, 2, 3, 4]),
            ],//码类型：0商品基础二维码，1序列号二维码，2批次号二维码，3条形码，库存ID
            [
                'batch_no.required' => '参数`码编号`缺失',
                'storage_id.required' => '参数`库存主键id`缺失',
                'storage_id.integer' => '参数`库存主键id`仅能为数字',
                'code_type.required' => '参数`码类型`缺失',
                'code_type.in' => '参数`码类型`有误！',
                /*    'shelf_id.required' => '参数`货架ID`缺失',
                    'location_id.required' => '参数`库位ID`缺失',
                    'shelf_id.integer' => '参数`货架ID`,必须为整数！',
                    'location_id.integer' => '参数`库位ID`,必须为整数！',*/
            ]
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['time'] = time();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();

        $result = StorageManageService::scanCodesInStorage($data);
        return response()->json($result);
    }

    /**
     * @直接出库
     * @created 在 2021/12/2 14:58 创建
     * @param Request $request
     * @author: Sun Wu
     */
    public function directOutStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//库存物料id
            'num' => 'required|numeric|min:0',//出库数量
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['time'] = time();
        $data['label_id'] = empty($data['label_id']) ? '' : $data['label_id'];
        $data['label_name'] = empty($data['label_name']) ? '' : $data['label_name'];

        $this->operateLog('直接出库', $data, $data['time']);

        $result = StorageManageService::directOutStorage($data);

        CommonService::operateResult($data['user_id'], $data['time'], $result);
        return response()->json(
            $result
        );
    }

    /**
     * @设置低库存预警数
     * @created 在 2021/11/30 16:54 创建
     * @param Request $request
     * @author: Sun Wu
     */
    public function setAlertNum(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',//库存物料id
            'alert_num' => 'required|numeric|min:0'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $time = time();
        $data['logTime'] = $time;
        $this->operateLog('设置低库存预警数', $data, $time);
        $result = StorageManageService::setAlertNum($data);
        CommonService::operateResult($this->getUserId(), $time, $result);
        return response()->json(
            $result
        );
    }

    /**
     * @删除
     * @created 在 2021/11/30 17:26 创建
     * @param Request $request
     * @author: Sun Wu
     */
    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//库存物料id
            //'model_type' => ['required',Rule::in([1,2])],//操作模式类型
        ], [
            'id.integer' => '参数主键id，必须为数字',
            /* 'model_type.required' => '操作模式类型，不能为空！',
             'model_type.in' =>'操作模式类型1或2'*/
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        return response()->json(
            StorageManageService::del($data)
        );
    }

    public function detail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',//库存物料id
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $this->log('查看库存详情', $data);
        return $this->success(StorageManageService::detail($data));
    }

    public function usedSerialList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type_id' => 'required',//商品id
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return $this->success(StorageManageService::usedSerialList($data));
    }

    /**
     * 套件返仓
     */
    public function returnPackageStore(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storage_manage_id' => 'required|integer',
            'product_id' => 'required|integer',
            'product_num' => 'required',
        ], [
            'storage_manage_id.required' => '参数`库存主键id`缺失',
            'storage_manage_id.integer' => '参数`库存主键id`仅能为数字',
            'product_id.required' => '参数`套件主键id`缺失',
            'product_id.integer' => '参数`套件主键id`仅能为数字',
            'product_num.required' => '参数`套件数量`缺失',
            /* 'product_num.integer' => '参数`套件数量`仅能为数字', */
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['time'] = time();
        $this->operateLog('套件返仓', $data, $data['time'], '返仓成功!');
        $result = storageManageService::handleReturnPackageStore($data);
        CommonService::operateResult($data['user_id'], $data['time'], $result);
        return response()->json($result);
    }

    /**
     * 库存查看序列号
     * Author: Sw
     * Created at 2023/2/28 9:37
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function serialList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',
            'type_id' => 'required|integer',
        ], [
            'id.required' => '参数`库存主键id`缺失',
            'id.integer' => '参数`库存主键id`仅能为数字',
            'type_id.required' => '参数`商品或套餐id`缺失',
            'type_id.integer' => '参数`商品或套餐id`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        return $this->success(storageManageService::serialList($data));
    }

    public function materielStorageList(Request $request): \Illuminate\Http\JsonResponse
    {
        if (!empty($id = $request->input('id'))) {
            return $this->success(
                StorageManageService::materielStorageList($id)
            );
        }

        return $this->success();
    }

    /**
     * 快速出入库同步价格
     * @param Request $request
     */
    public function getSyncPrice(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',
        ],
            [
                'id.required' => '参数`商品主键id`缺失',
            ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();
        if (empty($data['order_type'])) $data['order_type'] = 0;
        switch ($data['order_type']) {
            case 1://销售单
                $result = SellService::getSyncPrice($data);
                break;
            case 2://采购单
                $result = MaterielService::getSyncPrice($data);
                break;
            case 3://换货单
                $result = BarterService::getSyncPrice($data);
                break;
            default:
                $result = SellService::getSyncPrice($data);
                break;
        }
        return success($result);
    }

    /**
     * @批量删除
     * @created 2023-9-21
     * @param Request $request
     * @author: zlf
     */
    public function batchDel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids' => 'required',//库存id
            //'model_type' => ['required',Rule::in([1,2])],//操作模式类型
        ], [
            'ids.required' => '主键id,不能为空',
            /*'model_type.required' => '操作模式类型，不能为空！',
            'model_type.in' =>'操作模式类型1或2'*/
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        //$this->log('批量删除库存信息', $data);
        return response()->json(StorageManageService::batchDel($data));
    }

    /**
     * 修改预警数
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updAlertNum(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//库存id
            'alert_num' => 'numeric|min:0'
        ], [
            'id.required' => '请选择，要修改的预警库存行！',
            'id.integer' => '库存id，必须为整数！',
            'alert_num.numeric' => '预警数只能为数字',
            'alert_num.min' => '预警数最小只能为0',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $this->log('修改预警数', $data, '已修改！');
        $bool = StorageManageService::updAlertNum($data);
        if ($bool)
            return success();
        else
            return fail('', '修改失败');
    }

    /**
     * 删除序列号（适用于批量）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delSerialNo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids' => 'required',//库存id
        ], [
            'id.required' => '请选择，要删除的序列号！',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $this->log('修改预警数', $data);
        return StorageManageService::delSerialNo($data);
    }

    /**
     * 修改批次号
     * @param Request $request
     */
    public function updBatchNo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',//批次号id
        ], [
            'id.required' => '请选择，要修改的批次号！',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();

        $time = time();
        $this->operateLog('修改批次号', $data, $time);
        if (isset($data['expiration_date'])) {
            if ($data['expiration_date'] <= 0) {
                $data['expiration_date'] = "";
            }
        }
        if (isset($data['warning_time'])) {
            if ($data['warning_time'] <= 0) {
                $data['warning_time'] = "";
            }
        }
        if (!empty($data['expiration_date']) && !empty($data['warning_time'])) {
            if ($data['expiration_date'] < $data['warning_time']) {
                return fail('', '预警时间不能大于保质期');
            }
        }
        $data['production_time'] = !empty($data['production_time']) ? strtotime($data['production_time']) : "";
        $data['delivery_time'] = !empty($data['delivery_time']) ? strtotime($data['delivery_time']) : "";
        $res = StorageManageService::updBatchNo($data);
        $data['user_id'] = $this->getUserId();
        if ($res['code'] == 0) {
            if (!empty($res['data'])) {
                $ossClient = new OssClient(
                    config('app.aliyun_oss_key'),
                    config('app.aliyun_oss_secret'),
                    config('app.aliyun_oss_endpoint')
                );
                foreach ($res['data'] as $dVal) {
                    $substrUrl = explode('uploads', $dVal);
                    if (!empty($substrUrl[1]))
                        $ossClient->deleteObject(config('app.aliyun_oss_bucket'), 'uploads' . $substrUrl[1]);
                }
            }
            CommonService::operateResult($data['user_id'], $time, $data, $res['reg']);
            return success();
        } else {
            return fail('', 修改失败);
        }
    }

    /**
     * 批次列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 16:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function chooseBatchList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//页面大小
        ], [
            'id.required' => '参数`库存主键id`缺失',
            'id.integer' => '参数`库存主键id`仅能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        if (!isset($data['sort'])) {
            //是否使用最新的批次号:0否，1是
            $data['sort'] = !empty($this->isUseNewestBatchNo()) ? 'DESC' : 'ASC';
        }
        $result = StorageManageService::ChooseBatchList($data);
        return response()->json(['code' => 0, 'msg' => 'success', 'data' => $result]);
    }

    /**
     * 库存直接入库-仓库模式
     * @param Request $request
     * 2024/5/15 17:32
     * Author: zlf
     * @return \Illuminate\Http\JsonResponse
     */
    public function warehouseStorageManageIn(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storage_id' => 'required|integer',//仓库主键
            'type_id' => 'required|integer',//商品主键
            'num' => 'required|numeric|min:0'
        ], [
            'storage_id.required' => '参数`仓库主键id`缺失',
            'storage_id.integer' => '参数`仓库主键id`仅能为数字',
            'type_id.required' => '参数`商品主键id`缺失',
            'type_id.integer' => '参数`仓库主键id`仅能为数字',
            'num.required' => '参数`数量`缺失',
            'num.numeric' => '参数`数量`仅能为数字',
            'num.min' => '参数`数量`最小仅能为0',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['time'] = time();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['label_id'] = empty($data['label_id']) ? '' : $data['label_id'];

//        $this->log('库存直接入库',var_export($data, true));
        $this->operateLog('库存直接入库-仓库模式', $data, $data['time']);

        $result = StorageManageService::warehouseStorageManageIn($data);
        CommonService::operateResult($data['user_id'], $data['time'], $result);
        return response()->json($result);
    }

    /**
     * @直接出库
     * @created 在 2024/5/16 14:58 创建
     * @param Request $request
     * @author: zlf
     */
    public function warehouseStorageManageOut(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storage_id' => 'required|integer',//仓库主键
            'type_id' => 'required|integer',//商品主键
            'num' => 'required|numeric|min:0'
        ], [
            'storage_id.required' => '参数`仓库主键id`缺失',
            'storage_id.integer' => '参数`仓库主键id`仅能为数字',
            'type_id.required' => '参数`商品主键id`缺失',
            'type_id.integer' => '参数`仓库主键id`仅能为数字',
            'num.required' => '参数`数量`缺失',
            'num.numeric' => '参数`数量`仅能为数字',
            'num.min' => '参数`数量`最小仅能为0',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['time'] = time();
        $data['label_id'] = empty($data['label_id']) ? '' : $data['label_id'];
        $data['label_name'] = empty($data['label_name']) ? '' : $data['label_name'];

        $this->operateLog('直接出库-仓库模式', $data, $data['time']);

        $result = StorageManageService::warehouseStorageManageOut($data);

        CommonService::operateResult($data['user_id'], $data['time'], $result);
        return response()->json($result);
    }

    /**
     *扫码调拨
     * Author: zlf
     * Created at 2024/5/28 14:02
     * @param Request $request
     * @return void
     */
    public function scanCodeAllot(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'batch_no' => 'required',//码编号
            'code_type' => ['required',
                Rule::in([
                    0, 1, 2, 3
                ])],//码类型：0商品基础二维码，1序列号二维码，2批次号二维码，3条形码或库存码
            'out_storage_id' => 'required|integer',//出库仓库id
            'out_shelf_id' => 'required|integer',//出库货架ID
            'out_location_id' => 'required|integer',//出库库位ID
            'in_storage_id' => 'required|integer',//入库仓库ID
            'in_shelf_id' => 'required|integer',//入库货架ID
            'in_location_id' => 'required|integer',//入库库位ID
        ], [
            'batch_no.required' => '参数`码编号`缺失',
            'code_type.required' => '参数`码的类型`缺失',
            'code_type.in' => '参数`码的类型`有误',
            'out_storage_id.required' => '参数`出库仓库ID`缺失',
            'out_shelf_id.required' => '参数`出库货架ID`缺失',
            'out_location_id.required' => '参数`出库库位ID`缺失',
            'in_storage_id.required' => '参数`入库仓库ID`缺失',
            'in_shelf_id.required' => '参数`入库货架ID`缺失',
            'in_location_id.required' => '参数`入库库位ID`缺失',
            'out_storage_id.integer' => '参数`出库仓库ID`,必须为整数！',
            'out_shelf_id.integer' => '参数`出库货架ID`,必须为整数！',
            'out_location_id.integer' => '参数`出库库位ID`,必须为整数！',
            'in_storage_id.integer' => '参数`入库仓库ID`,必须为整数！',
            'in_shelf_id.integer' => '参数`入库货架ID`,必须为整数！',
            'in_location_id.integer' => '参数`入库库位ID`,必须为整数！',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $time = time();
        $this->operateLog('扫码调拨', $data, $time);
        $data['time'] = $time;
        return response()->json(ScanCodeAllotService::scanCodeAllot($data));

    }
}
